﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using TravelSite.DAL;
using TravelSite.DAL.Repositories;
using TravelSite.Entities;
using TravelSite.Code;
using System.Web.Security;
using System.Globalization;

namespace TravelSite.Controls
{
    public partial class ContactDetails : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadCombo();
            }

        }

        private void LoadCombo()
        {
            using (var repo = RepositoryFactory.ResolveRepository<UserRepository>())
            {
                ddlAgentId.DataSource = repo.AgentsCombo(false);
                ddlAgentId.DataBind();
            }

            using (var repo = RepositoryFactory.ResolveRepository<ContactRepository>())
            {
                ddlCountryId.DataSource = repo.CountriesCombo(false, false);
                ddlCountryId.DataBind();
                ddlCountryId.SelectedValue = "1";
                LoadStates();

                ddlBankInfoPaymentId.DataSource = repo.PaymentsCombo(false, true);
                ddlBankInfoPaymentId.DataBind();
                ddlBankInfoPaymentId.SelectedValue = "-1";

                ddlEmailSettingId.DataSource = repo.EmailSettingsCombo(false, true);
                ddlEmailSettingId.DataBind();
                ddlEmailSettingId.SelectedValue = "-1";
            }

            ddlYearDOB.Items.Add(new ListItem("(year)", "-1"));
            ddlYearDOB.SelectedValue = "-1";
            for (int i = DateTime.Now.Year; i >= DateTime.Now.Year - 150; --i)
                ddlYearDOB.Items.Add(new ListItem(i.ToString(), i.ToString()));

            ddlDayDOB.Items.Add(new ListItem("(day)", "-1"));
            ddlDayDOB.SelectedValue = "-1";
            for (int i = 1; i <= 31; ++i)
                ddlDayDOB.Items.Add(new ListItem(i.ToString("00"), i.ToString()));
        }

        private void LoadStates()
        {
            using (var repo = RepositoryFactory.ResolveRepository<ContactRepository>())
            {
                ddlStateId.DataSource = repo.StatesCombo(false, true, Convert.ToInt32(ddlCountryId.SelectedValue));
                ddlStateId.DataBind();
            }

            ddlStateId.Items[0].Text = ddlCountryId.SelectedValue == "2" ? "(Select Province)" : "(Select State)";
            lblState.Text = ddlCountryId.SelectedValue == "2" ? "Province" : "State";
            lblZipCode.Text = (ddlCountryId.SelectedValue == "2" ? "Postal" : "Zip") + " Code";
        }

        private void LoadComments()
        {
            if (!string.IsNullOrEmpty(hdId.Text))
            {
                string contactId = hdId.Text;

                using (var repo = RepositoryFactory.ResolveRepository<ContactCommentRepository>())
                {
                    rptComments.DataSource = repo.FindByContact(Convert.ToInt32(contactId));
                    rptComments.DataBind();
                }
            }
        }

        protected void upDetails_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request["__EVENTTARGET"]))
                if (Request["__EVENTTARGET"] != upDetails.ClientID)
                    return;

            if (!string.IsNullOrEmpty(Request["__EVENTARGUMENT"]))
            {
                hdId.Text = Request["__EVENTARGUMENT"];

                if (hdId.Text != "-1")
                {
                    using (var repo = RepositoryFactory.ResolveRepository<ContactRepository>())
                    {
                        Contact itm = repo.Find(Convert.ToInt32(hdId.Text));
                        lblDialogTitle.Text = String.Format("EDIT CLIENT: {0}", itm.FullName);
                        txtFirstName.Text = itm.FirstName;
                        txtLastName.Text = itm.LastName;
                        txtEmail.Text = itm.Email;
                        if (itm.EmailSettingId.HasValue)
                            ddlEmailSettingId.SelectedValue = itm.EmailSettingId.Value.ToString();
                        else
                            ddlEmailSettingId.Text = "-1";
                        txtMPhone.Text = itm.MPhone;
                        txtWPhone.Text = itm.WPhone;
                        txtHPhone.Text = itm.HPhone;
                        txtAddress1.Text = itm.Address1;
                        txtAddress2.Text = itm.Address2;
                        txtCity.Text = itm.City;
                        txtCompanyName.Text = itm.CompanyName;
                        txtJobTitle.Text = itm.JobTitle;
                        txtZip.Text = itm.Zip;
                        txtPartnerFirstName.Text = itm.PartnerFirstName;
                        txtPartnerLastName.Text = itm.PartnerLastName;
                        if (itm.DateOfBirth.HasValue)
                        {
                            ddlYearDOB.SelectedValue = itm.DateOfBirth.Value.Year.ToString();
                            ddlMonthDOB.SelectedValue = itm.DateOfBirth.Value.Month.ToString();
                            ddlDayDOB.SelectedValue = itm.DateOfBirth.Value.Day.ToString();
                        }
                        else
                        {
                            ddlYearDOB.SelectedValue = "-1";
                            ddlMonthDOB.SelectedValue = "-1";
                            ddlDayDOB.SelectedValue = "-1";
                        }
                        ddlAgentId.SelectedValue = itm.AgentId.ToString();
                        ddlCountryId.SelectedValue = itm.CountryId.ToString();
                        LoadStates();
                        ddlStateId.SelectedValue = (itm.StateId ?? -1).ToString();
                        txtNotes.Text = itm.Notes;
                        txtPin.Text = itm.Pin;

                        if (itm.BankInfoDate.HasValue)
                            txtBankInfoDate.Text = itm.BankInfoDate.Value.ToString("d", new CultureInfo("en-US"));
                        else
                            txtBankInfoDate.Text = "";
                        if (itm.BankInfoAmount.HasValue)
                            txtBankInfoAmount.Text = itm.BankInfoAmount.Value.ToString("N", new CultureInfo("en-US"));
                        else
                            txtBankInfoAmount.Text = "";
                        if (itm.BankInfoPaymentId.HasValue)
                            ddlBankInfoPaymentId.SelectedValue = itm.BankInfoPaymentId.Value.ToString();
                        else
                            ddlBankInfoPaymentId.SelectedValue = "-1";
                        InitVacationCompanyDropDownList(itm.VacationCompanyId ?? 0);

                        txtTourDate.Text = itm.TourDate;
                        txtTourTime.Text = itm.TourTime;
                        InitHotelDropDownList(itm.TourHotelId ?? 0);
                        InitTourCompanyDropDownList(itm.TourCompanyId ?? 0);
                        if (itm.TourHotelCost.HasValue)
                            txtTourHotelCost.Text = itm.TourHotelCost.Value.ToString("N", new CultureInfo("en-US"));
                        else
                            txtTourHotelCost.Text = "";
                        txtTourNotes.Text = itm.TourNotes;
                        txtVerified.Text = itm.Verified;
                        txtVerificationSend.Text = itm.VerificationsSend;
                        txtConfirmationNumber.Text = itm.ConfirmationNumber;
                        if (itm.PackagePrice.HasValue)
                            txtPackagePrice.Text = itm.PackagePrice.Value.ToString("N", new CultureInfo("en-US"));
                        else
                            txtPackagePrice.Text = "";
                        txtUpgradeFee.Text = itm.UpgradeFee.ToString();
                        txtTourGift.Text = itm.Gift;
                        txtGiftCost.Text = itm.GiftCost.ToString();
                        txtTourComments.Text = itm.Comments;

                        InitWholesalerDropDownList(itm.WholesalerId ?? 0);
                        txtHotelbedsInvoiceNumber.Text = itm.HotelbedsInvoiceNumber;
                        txtHotelbedsResNumber.Text = itm.HotelbedsResNumber;
                        if (itm.HotelbedsBookedDate.HasValue)
                            txtHotelbedsBookedDate.Text = itm.HotelbedsBookedDate.Value.ToString("d", new CultureInfo("en-US"));
                        else
                            txtHotelbedsBookedDate.Text = "";
                        if (itm.HotelbedsArrivalDate.HasValue)
                            txtHotelbedsArrivalDate.Text = itm.HotelbedsArrivalDate.Value.ToString("d", new CultureInfo("en-US"));
                        else
                            txtHotelbedsArrivalDate.Text = "";
                        if (itm.HotelbedsDepartureDate.HasValue)
                            txtHotelbedsDepartureDate.Text = itm.HotelbedsDepartureDate.Value.ToString("d", new CultureInfo("en-US"));
                        else
                            txtHotelbedsDepartureDate.Text = "";
                        if (itm.HotelbedsPaymentDate.HasValue)
                            txtHotelbedsPaymentDate.Text = itm.HotelbedsPaymentDate.Value.ToString("d", new CultureInfo("en-US"));
                        else
                            txtHotelbedsPaymentDate.Text = "";
                        if (itm.HotelbedsTotalWholesaleCost.HasValue)
                            txtHotelbedsTotalWholesaleCost.Text = itm.HotelbedsTotalWholesaleCost.Value.ToString("N", new CultureInfo("en-US"));
                        else
                            txtHotelbedsTotalWholesaleCost.Text = "";
                        if (itm.HotelbedsExpoPaidDate.HasValue)
                            txtHotelbedsExpoPaidDate.Text = itm.HotelbedsExpoPaidDate.Value.ToString("d", new CultureInfo("en-US"));
                        else
                            txtHotelbedsExpoPaidDate.Text = "";
                        if (itm.HotelbedsTotalPaid.HasValue)
                            txtHotelbedsTotalPaid.Text = itm.HotelbedsTotalPaid.Value.ToString("N", new CultureInfo("en-US"));
                        else
                            txtHotelbedsTotalPaid.Text = "";
                        txtHotelbedsCheckNumber.Text = itm.HotelbedsCheckNumber;
                        if (itm.HotelbedsHBPaidDate.HasValue)
                            txtHotelbedsHBPaidDate.Text = itm.HotelbedsHBPaidDate.Value.ToString("d", new CultureInfo("en-US"));
                        else
                            txtHotelbedsHBPaidDate.Text = "";

                        tabCommentHeader.Visible = true;
                        tabCommentContent.Visible = true;

                        btnContracts.Visible = true;
                        btnSave.Visible = true;
                    }
                }
                else
                {
                    lblDialogTitle.Text = "ADD NEW CLIENT";
                    txtFirstName.Text = "";
                    txtLastName.Text = "";
                    txtEmail.Text = "";
                    ddlEmailSettingId.SelectedValue = "-1";
                    txtMPhone.Text = "";
                    txtWPhone.Text = "";
                    txtHPhone.Text = "";
                    txtAddress1.Text = "";
                    txtAddress2.Text = "";
                    txtCity.Text = "";
                    txtCompanyName.Text = "";
                    txtJobTitle.Text = "";
                    txtZip.Text = "";
                    txtPartnerFirstName.Text = "";
                    txtPartnerLastName.Text = "";
                    ddlYearDOB.SelectedValue = "-1";
                    ddlMonthDOB.SelectedValue = "-1";
                    ddlDayDOB.SelectedValue = "-1";
                    txtNotes.Text = "";
                    txtPin.Text = "";
                    ddlCountryId.SelectedValue = "1";
                    LoadStates();
                    if (Roles.IsUserInRole("agent"))
                    {
                        ddlAgentId.SelectedValue = (Page as BasePage).CurrentUserId.ToString();
                    }

                    txtBankInfoDate.Text = "";
                    txtBankInfoAmount.Text = "";
                    ddlBankInfoPaymentId.SelectedValue = "-1";
                    InitVacationCompanyDropDownList(0);

                    txtTourDate.Text = "";
                    txtTourTime.Text = "";
                    InitHotelDropDownList(0);
                    InitTourCompanyDropDownList(0);
                    txtTourHotelCost.Text = "";
                    txtTourNotes.Text = "";
                    txtVerified.Text = "";
                    txtVerificationSend.Text = "";
                    txtConfirmationNumber.Text = "";
                    txtPackagePrice.Text = "";
                    txtUpgradeFee.Text = "";
                    txtTourGift.Text = "";
                    txtGiftCost.Text = "";
                    txtTourComments.Text = "";

                    InitWholesalerDropDownList(0);
                    txtHotelbedsInvoiceNumber.Text = "";
                    txtHotelbedsResNumber.Text = "";
                    txtHotelbedsBookedDate.Text = "";
                    txtHotelbedsArrivalDate.Text = "";
                    txtHotelbedsDepartureDate.Text = "";
                    txtHotelbedsPaymentDate.Text = "";
                    txtHotelbedsTotalWholesaleCost.Text = "";
                    txtHotelbedsExpoPaidDate.Text = "";
                    txtHotelbedsTotalPaid.Text = "";
                    txtHotelbedsCheckNumber.Text = "";
                    txtHotelbedsHBPaidDate.Text = "";
                    
                    tabCommentHeader.Visible = false;
                    tabCommentContent.Visible = false;

                    btnSave.Visible = true;
                    btnContracts.Visible = false;
                }

                ddlAgentId.Enabled = !Roles.IsUserInRole("agent");
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ShowEdit", "openDetails();", true);
            }
        }

        protected void upComment_Load(object sender, EventArgs e)
        {
            LoadComments();
        }

        protected void ddlCountry_SelectedIndexChanged(Object sender, EventArgs e)
        {
            LoadStates();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            DateTime? bankInfoDate = null;
            try
            {
                if (!string.IsNullOrEmpty(txtBankInfoDate.Text))
                    bankInfoDate = DateTime.ParseExact(txtBankInfoDate.Text, "d", new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Bank Info Date not valid!'); }, 150);", true);
                return;
            }

            decimal? bankInfoAmount = null;
            try
            {
                if (!string.IsNullOrEmpty(txtBankInfoAmount.Text))
                    bankInfoAmount = decimal.Parse(txtBankInfoAmount.Text, new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Bank Info Amount not valid!'); }, 150);", true);
                return;
            }

            decimal? tourHotelCost = null;
            try
            {
                if (!string.IsNullOrEmpty(txtTourHotelCost.Text))
                    tourHotelCost = decimal.Parse(txtTourHotelCost.Text, new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Tour Hotel Cost not valid!'); }, 150);", true);
                return;
            }

            int? upgradeFee = null;
            try
            {
                if (!string.IsNullOrEmpty(txtUpgradeFee.Text))
                    upgradeFee = Int32.Parse(txtUpgradeFee.Text);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Upgrade Fee not valid!'); }, 150);", true);
                return;
            }

            int? giftCost = null;
            try
            {
                if (!string.IsNullOrEmpty(txtGiftCost.Text))
                    giftCost = Int32.Parse(txtGiftCost.Text);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Gift Cost not valid!'); }, 150);", true);
                return;
            }

            decimal? hotelbedsTotalWholesaleCost = null;
            try
            {
                if (!string.IsNullOrEmpty(txtHotelbedsTotalWholesaleCost.Text))
                    hotelbedsTotalWholesaleCost = decimal.Parse(txtHotelbedsTotalWholesaleCost.Text, new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Hotelbeds Total Wholesale Cost not valid!'); }, 150);", true);
                return;
            }

            decimal? hotelbedsTotalPaid = null;
            try
            {
                if (!string.IsNullOrEmpty(txtHotelbedsTotalPaid.Text))
                    hotelbedsTotalPaid = decimal.Parse(txtHotelbedsTotalPaid.Text, new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Hotelbeds Total Paid not valid!'); }, 150);", true);
                return;
            }

            DateTime? hotelbedsBookedDate = null;
            try
            {
                if (!string.IsNullOrEmpty(txtHotelbedsBookedDate.Text))
                    hotelbedsBookedDate = DateTime.ParseExact(txtHotelbedsBookedDate.Text, "d", new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Hotelbeds Booked Date not valid!'); }, 150);", true);
                return;
            }

            DateTime? hotelbedsArrivalDate = null;
            try
            {
                if (!string.IsNullOrEmpty(txtHotelbedsArrivalDate.Text))
                    hotelbedsArrivalDate = DateTime.ParseExact(txtHotelbedsArrivalDate.Text, "d", new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Hotelbeds Arrival Date not valid!'); }, 150);", true);
                return;
            }

            DateTime? hotelbedsDepartureDate = null;
            try
            {
                if (!string.IsNullOrEmpty(txtHotelbedsDepartureDate.Text))
                    hotelbedsDepartureDate = DateTime.ParseExact(txtHotelbedsDepartureDate.Text, "d", new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Hotelbeds Departure Date not valid!'); }, 150);", true);
                return;
            }

            DateTime? hotelbedsPaymentDate = null;
            try
            {
                if (!string.IsNullOrEmpty(txtHotelbedsPaymentDate.Text))
                    hotelbedsPaymentDate = DateTime.ParseExact(txtHotelbedsPaymentDate.Text, "d", new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Hotelbeds Payment Date not valid!'); }, 150);", true);
                return;
            }

            DateTime? hotelbedsExpoPaidDate = null;
            try
            {
                if (!string.IsNullOrEmpty(txtHotelbedsExpoPaidDate.Text))
                    hotelbedsExpoPaidDate = DateTime.ParseExact(txtHotelbedsExpoPaidDate.Text, "d", new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Hotelbeds Date YVD Paid to Expo not valid!'); }, 150);", true);
                return;
            }

            DateTime? hotelbedsHBPaidDate = null;
            try
            {
                if (!string.IsNullOrEmpty(txtHotelbedsHBPaidDate.Text))
                    hotelbedsHBPaidDate = DateTime.ParseExact(txtHotelbedsHBPaidDate.Text, "d", new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Date Expo Paid HB not valid!'); }, 150);", true);
                return;
            }

            Contact itm = new Contact();

            itm.LastName = txtLastName.Text;
            itm.FirstName = txtFirstName.Text;
            itm.Email = txtEmail.Text;
            itm.EmailSettingId = ddlEmailSettingId.SelectedValue == "-1" ? (int?)null : Convert.ToInt32(ddlEmailSettingId.SelectedValue);
            itm.WPhone = txtWPhone.Text;
            itm.HPhone = txtHPhone.Text;
            itm.MPhone = txtMPhone.Text;
            itm.Address1 = txtAddress1.Text;
            itm.Address2 = txtAddress2.Text;
            itm.City = txtCity.Text;
            itm.CompanyName = txtCompanyName.Text;
            itm.JobTitle = txtJobTitle.Text;
            itm.Zip = txtZip.Text;
            itm.AgentId = Convert.ToInt32(ddlAgentId.SelectedValue);
            itm.CountryId = Convert.ToInt32(ddlCountryId.SelectedValue);
            itm.StateId = ddlStateId.SelectedValue == "-1" ? null : (int?)Convert.ToInt32(ddlStateId.SelectedValue);
            itm.PartnerFirstName = txtPartnerFirstName.Text;
            itm.PartnerLastName = txtPartnerLastName.Text;
            if ((ddlDayDOB.SelectedValue != "-1") && (ddlMonthDOB.SelectedValue != "-1") && (ddlYearDOB.SelectedValue != "-1"))
                itm.DateOfBirth = new DateTime(Convert.ToInt32(ddlYearDOB.SelectedValue), Convert.ToInt32(ddlMonthDOB.SelectedValue), Convert.ToInt32(ddlDayDOB.SelectedValue));
            else
                itm.DateOfBirth = null;
            itm.Notes = txtNotes.Text;
            itm.Pin = txtPin.Text;

            itm.BankInfoAmount = bankInfoAmount;
            itm.BankInfoDate = bankInfoDate;
            itm.BankInfoPaymentId = ddlBankInfoPaymentId.SelectedValue == "-1" ? (int?)null : Convert.ToInt32(ddlBankInfoPaymentId.SelectedValue);
            itm.VacationCompanyId = Convert.ToInt32(ddlVacationCompanyId.SelectedValue);

            itm.TourDate = txtTourDate.Text;
            itm.TourTime = txtTourTime.Text;
            itm.TourCompanyId = Int32.Parse(dpdnTourCompanyId.SelectedValue);
            int tourId = 0;
            Int32.TryParse(dpdnTourHotel.SelectedValue, out tourId);
            itm.TourHotelId = tourId > 0 ? tourId : new int?();
            itm.TourHotelCost = tourHotelCost;
            itm.TourNotes = txtTourNotes.Text;
            itm.Verified = txtVerified.Text;
            itm.VerificationsSend = txtVerificationSend.Text;
            itm.ConfirmationNumber = txtConfirmationNumber.Text;
            itm.UpgradeFee = upgradeFee;
            itm.Gift = txtTourGift.Text;
            itm.GiftCost = giftCost;
            itm.Comments = txtTourComments.Text;

            itm.WholesalerId = Int32.Parse(ddlWholesalerId.SelectedValue);
	        itm.HotelbedsInvoiceNumber = txtHotelbedsInvoiceNumber.Text;
	        itm.HotelbedsResNumber = txtHotelbedsResNumber.Text;
	        itm.HotelbedsBookedDate = hotelbedsBookedDate;
	        itm.HotelbedsArrivalDate = hotelbedsArrivalDate;
            itm.HotelbedsDepartureDate = hotelbedsDepartureDate;
            itm.HotelbedsPaymentDate = hotelbedsPaymentDate;
            itm.HotelbedsTotalWholesaleCost = hotelbedsTotalWholesaleCost;
            itm.HotelbedsExpoPaidDate = hotelbedsExpoPaidDate;
            itm.HotelbedsTotalPaid = hotelbedsTotalPaid;
            itm.HotelbedsCheckNumber = txtHotelbedsCheckNumber.Text;
            itm.HotelbedsHBPaidDate = hotelbedsHBPaidDate;

            using (var repo = RepositoryFactory.ResolveRepository<ContactRepository>())
            {

                if (!string.IsNullOrEmpty(itm.Pin))
                {
                    if (!repo.CheckPin(Convert.ToInt32(hdId.Text), itm.Pin))
                    {
                        ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "alert('Such Pin already exists!');", true);
                        return;
                    }
                }

                if (hdId.Text == "-1")
                    repo.Insert(itm);

                else
                {
                    itm.ContactId = Convert.ToInt32(hdId.Text);
                    repo.Update(itm);
                }
            }
            ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "DialogClose", "$('#editDialog').dialog('close');", true);
            (this.Page as BaseDataPage).LoadData();
        }

        protected void btnContracts_Click(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("ContactManagementContracts.aspx?c={0}", hdId.Text), true);
        }

        protected void btnAddComment_Click(object sender, EventArgs e)
        {
            ContactComment itm = new ContactComment();
            itm.AddDateTime = DateTime.Now;
            itm.ContactId = Convert.ToInt32(hdId.Text);
            itm.UserId = (Page as BasePage).CurrentUserId.Value;
            itm.Comment = tbCommentAdd.Text;

            using (var repo = RepositoryFactory.ResolveRepository<ContactCommentRepository>())
            {
                repo.Insert(itm);
            }

            tbCommentAdd.Text = "";
            LoadComments();
        }
        
        private void InitHotelDropDownList(int selectedValue)
        {
            List<Tour> tours = new List<Tour>();
            tours.Add(new Tour() { TourId = 0, TourName = "" });

            using (var tourRepo = RepositoryFactory.ResolveRepository<TourRepository>())
            {
                tours.AddRange(tourRepo.FindAll());
            }
            dpdnTourHotel.DataSource = tours;
            dpdnTourHotel.DataBind();
            dpdnTourHotel.SelectedValue = selectedValue.ToString();
        }

        private void InitVacationCompanyDropDownList(int selectedValue)
        {
            List<VacationCompany> vacCompany = new List<VacationCompany>();
            using (var vacCompanyRepo = RepositoryFactory.ResolveRepository<VacationCompanyRepository>())
            {
                vacCompany = vacCompanyRepo.FindAll().ToList();
            }
            ddlVacationCompanyId.DataSource = vacCompany;
            ddlVacationCompanyId.DataBind();
            ddlBookingVacationCompanyId.DataSource = vacCompany;
            ddlBookingVacationCompanyId.DataBind();
            if (selectedValue == 0)
            {
                VacationCompany defCompany = vacCompany.FirstOrDefault(x=> x.IsDefault);
                if (defCompany != null)
	            {
                    ddlVacationCompanyId.SelectedValue = defCompany.VacationCompanyId.ToString();
                    ddlBookingVacationCompanyId.SelectedValue = defCompany.VacationCompanyId.ToString();
	            }
            }
            else
            {
                ddlVacationCompanyId.SelectedValue = selectedValue.ToString();
                ddlBookingVacationCompanyId.SelectedValue = selectedValue.ToString();
            }
        }

        private void InitWholesalerDropDownList(int selectedValue)
        {
            List<Wholesaler> wholesalers = new List<Wholesaler>();
            using (var wholesalerRepo = RepositoryFactory.ResolveRepository<WholesalerRepository>())
            {
                wholesalers = wholesalerRepo.FindAll().ToList();
            }
            ddlWholesalerId.DataSource = wholesalers;
            ddlWholesalerId.DataBind();
            if (selectedValue == 0)
            {
                Wholesaler defWholesaler = wholesalers.FirstOrDefault(x => x.IsDefault);
                if (defWholesaler != null)
	            {
                    ddlWholesalerId.SelectedValue = defWholesaler.WholesalerId.ToString();
	            }
            }
            else
            {
                ddlWholesalerId.SelectedValue = selectedValue.ToString();
            }
        }

        private void InitTourCompanyDropDownList(int selectedValue)
        {
            List<TourCompany> tourCompanies = new List<TourCompany>();
            using (var tourCompanyRepo = RepositoryFactory.ResolveRepository<TourCompanyRepository>())
            {
                tourCompanies = tourCompanyRepo.FindAll().ToList();
            }
            dpdnTourCompanyId.DataSource = tourCompanies;
            dpdnTourCompanyId.DataBind();
            if (selectedValue == 0)
            {
                TourCompany defCompany = tourCompanies.FirstOrDefault(x => x.IsDefault);
                if (defCompany != null)
                {
                    dpdnTourCompanyId.SelectedValue = defCompany.TourCompanyId.ToString();
                }
            }
            else
            {
                dpdnTourCompanyId.SelectedValue = selectedValue.ToString();
            }
        }

        protected void ddlBookingVacationCompanyId_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlVacationCompanyId.SelectedIndex = ddlBookingVacationCompanyId.SelectedIndex;
        }

        protected void ddlVacationCompanyId_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlBookingVacationCompanyId.SelectedIndex = ddlVacationCompanyId.SelectedIndex;
        }
    }
}